#include <iostream>
#include <SDL_net.h>
#include "Networking.h"
#include "Client.h"
#include "Timer.h"
#include "Server.h"
#include "GMClientDisconnectRequest.h"
#include "GameMessageFactory.h"
#undef main

int main(int argc, char** argv)
{
#pragma region Memory Leaks
#ifdef WIN32
    // Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
    _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif//debug
#endif//win32
#pragma endregion

    SDL_Init(0);
    SDLNet_Init();

    GameMessage::StaticPrepareFactory();
    TheTimer::Instance();
    TheServer::Instance();
    TheClient::Instance();

    if(argc < 3 )
    {
        OUT_STRING("Usage: " << " @param1: IP to connect to, @param2: Port to connect via ");
        return 1;
    }
    OUT_STRING('\n'<< '\n' << "----Starting----");
    const char* ipAdd = argv[1];
    OUT_STRING("IP: " << ipAdd);

    int port = 0;
    OUT_STRING("Port: " << argv[2]);
    port = atoi(argv[2]);
    

    if(!TheClient::Instance()->ConnectToServer(std::string(ipAdd), port))
    {
        OUT_STRING("Connection Failed...");
        return 1;
    }
    OUT_STRING("Connection made...");
    int counter = 0;
    int request = 0;
    while( TheClient::Instance()->IsConnected() )
    {
        TheTimer::Instance()->Update();
        TheClient::Instance()->Update();
        SDL_Delay(10);
        counter++;
        if(counter % 10 == 0)
        {
            TheClient::Instance()->PingServer();
        }
        if(counter > 500)
        {
            if(request == 0)
            {
                OUT_STRING("Sending a disconnect request");
                GMClientDisconnectRequest gm;
                gm.SetID(TheClient::Instance()->GetID());
                TheClient::Instance()->SendToServer(gm);
                request++;                
            }
        }
    }


    TheClient::Instance()->ShutDown();
    TheTimer::Kill();
    TheServer::Kill();
    TheClient::Kill();
    TheGameMessageFactory::Kill();

    system("pause");
}
